<template>
  <div id="export-data-preview-div">
    <div id="export-data-preview" v-if="resType == 'table'">
      <div class="upload_struct_optinal_btn">
        <el-button class="bi-el-btn" type="button" @click="addData">新建</el-button>
        <el-button class="bi-el-btn" type="button" @click="modifyData" :disabled="modifyButtonDisabled">编辑</el-button>
        <el-button class="bi-el-btn" type="button" @click="deleteData" :disabled="deleteButtonDisabled">删除</el-button>
        <el-tooltip effect="light" content="导入数据前，请先导出数据模板" placement="bottom">
          <el-button class="bi-el-btn"
                     type="button"
                     icon="bi-ui-icon-irp-btn-import bi-ui-iconfont"
                     @click="importTableData">导入
          </el-button>
        </el-tooltip>
        <el-button class="bi-el-btn"
                   type="button"
                   icon="bi-ui-icon-irp-btn-export bi-ui-iconfont"
                   @click="doExportTableFile">导出
        </el-button>
        <el-button class="bi-el-btn"
                   type="button"
                   icon="bi-ui-icon-irp-btn-export bi-ui-iconfont"
                   @click="clearTableDatas">清空数据
        </el-button>
        <el-button
            class="bi-el-btn"
            type="button"
            @click="addFilterCondition"
            :disabled="conditionArr.length >= optionalTableHeaders.length">
          添加过滤条件
        </el-button>
      </div>
      <div class="filterAreaClass">
        <div v-for="(item, index) in conditionArr" class="conditionClass">
          <el-select
              @change="(e) => selectTableField(item.id,e)"
              :value="item.title"
              value-key="prop"
              class="conditionSelectClass"
              popper-class="bi-el-select-panel irp-domain_lys-popper">
            <el-option
                v-for="tableHeader in optionalTableHeaders"
                :key="tableHeader.prop"
                :label="tableHeader.title"
                :value="tableHeader"
                :disabled="!tableHeader.isOptionalConditionFields">
            </el-option>
          </el-select>
          <el-input v-model="item.value"></el-input>
          <el-button class="bi-el-btn" type="button" @click="deleteCondition(item)">删除</el-button>
        </div>
        <div style="margin-bottom: 12px;margin-left: -4px">
          <el-button
              class="bi-el-btn"
              type="button"
              @click="activeFilterCondition"
              v-show="conditionArr.length !== 0"
              style="height: 31px">
            查询
          </el-button>
        </div>
      </div>
      <div class="struce-optional-excel" :style="{ height: 'calc(100% - '+struceOptionalExcel+'px)' }">
          <el-table
              ref="excelOpTable"
              :data="tableData"
              tooltip-effect="dark"
              height="calc(100% - 60px)"
              v-loading="isloading"
              border
              class="bi-el-table bi-el-table-edit"
              @selection-change="handleSelectionChange"
              @row-click="rowClick">
            <el-table-column
                type="selection"
                align="center"
                width="55">
            </el-table-column>
            <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
                fixed="left">
              <template slot-scope="scope">
                {{currentPage === 1? ++scope.$index : (currentPage - 1) * pageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <template v-for="(item,index) in tableHearders">
              <el-table-column
                  :prop="item.prop"
                  :label="item.title"
                  :align="item.align"
                  :key="index"
                  header-align="left"
                  show-overflow-tooltip
                  :render-header="labelHeadrenderHeader">
                <template slot-scope="scope">
                  <span :title="scope.row[item.prop]"
                        :class="scope.row.isSelectedViewTarget ?' datamanageTreeScrollIntoViewTableItemTarget' : ''">
                    {{ scope.row[item.prop] }}
                  </span>
                </template>
              </el-table-column>
            </template>
          </el-table>
        <el-pagination
            class="bi-el-pagination"
            popper-class="bi-el-page-content"
            layout="total, prev, pager, next, jumper,sizes, slot"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100]"
            :page-size="pageSize"
            :pager-count=9
            :total="currentTotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </div>

    <div v-if="resType == 'table_dim' " id="export-data-preview-dim">
      <iframe id="iresinfoDimView" ref="iresinfoDimView" style="height: 100%; width: 100%;" frameborder="0"
              :src="iframeSrcUrl"></iframe>
    </div>
  </div>
</template>

<script>
import {ResAPI, inforesApi} from "@/api/irpApi.js";

export default {
  props: ["resCode", 'cruResType','cruResTitle'],
  data() {
    return {
      struceOptionalExcel: 60,
      tableData: [],
      tableHearders: [],
      optionalTableHeaders:[],
      pageSize: 20,
      currentPage: 1,
      currentTotal: 0,
      resGuid: '',
      isloading: false,
      iframeSrcUrl: '',
      resType: '',
      resTitle:'',
      cloumItdth: '180px',
      multipleTableSelection: [],
      modifyButtonDisabled: true,
      deleteButtonDisabled: true,
      conditionArr:[],
      lastTakeEffectedConditionArr:[],
      curTablePKNameArr:[],
      //当前调用弹框 处理类型，-1 初始状态 0新建  1编辑
      curProcessType: -1,
    }
  },
  watch:{
    multipleTableSelection: {
      handler: function(newValue) {
        if (newValue && newValue.length > 0) {

          if (newValue.length === 1)
            this.modifyButtonDisabled = false
          else
            this.modifyButtonDisabled = true

          this.deleteButtonDisabled = false
        }else{
          this.modifyButtonDisabled = true
          this.deleteButtonDisabled = true
        }
      }
    },
    resGuid:function(){
      //清空查询条件
      this.conditionArr.splice(0, this.conditionArr.length);
      this.lastTakeEffectedConditionArr.splice(0, this.lastTakeEffectedConditionArr.length);
    }
  },
  methods: {
    initData: function (guid, cruResType,cruResTitle) {
      this.resGuid = guid;
      this.resType = cruResType;
      this.resTitle = cruResTitle;

      if (this.resType == 'table_dim') {
        this.initDimData();
      } else {
        if (this.resGuid) {
          this.initStructFiled();
          this.$nextTick(() => {
            this.doFilterSearch();
          });
        }

      }
    },
    closeView: function () {
      this.resType = '';
    },

    //初始化维度数据
    initDimData: function () {
      inforesApi.getModelGuid({"guid": this.resGuid}).then((res) => {
        this.resGuid = res.data;
        this.iframeSrcUrl = this.$frontContextPath + "/dwh-app/dist/dim/dimMemberManager.html?hideBtnList=back-btn&frompage=editDim&dimGuid=" + this.resGuid;
      })
    },

    initStructFiled: function () {
      inforesApi.dataManageGetOriginalFieldInfos(this.resGuid).then((result) => {
        this.tableHearders = [];
        this.optionalTableHeaders = [];
        let structs = result.data;
        for (let i = 0; i < structs.length; i++) {
          const element = structs[i];
          const cruheard = {
            "prop": element.fieldName,
            "title": element.fieldTitle,
            "align": ((element.dataType == 8 || element.dataType == 3 || element.dataType == 5) ? 'right' : 'left'),
            "isOptionalConditionFields":true
          }
          this.tableHearders.push(cruheard);
          if (element.type !== 3) this.optionalTableHeaders.push(cruheard)
        }
        this.$nextTick(() => {
          let _this = this;
          if (this.$refs.excelOpTable) {
            setTimeout(function () {
              _this.$refs.excelOpTable.doLayout();
            }, 150)
          }
        });
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.doFilterSearch();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.doFilterSearch();
    },
    labelHeadrenderHeader(h, { column, $index }) {
      let width = 0
      // 新建一个 span
      let span = document.createElement('span');
      // 设置表头名称
      span.innerText = column.label;
      // 设置表头class
      span.className = 'getTextWidth'
      // 临时插入 document
      document.querySelector('body').appendChild(span)
      // 获取span标签的宽度
      width = document.querySelector('.getTextWidth').offsetWidth
      column.minWidth = width + 30;
      // 移除 document 中临时的 span
      document.querySelector('.getTextWidth').remove()
      return h('span', column.label);
    },
    // 表格多选
    handleSelectionChange(val) {
      this.multipleTableSelection = val;
    },
    //单击设置内容
    rowClick: function(data) {
      //设置选中状态
      this.$refs.excelOpTable.toggleRowSelection(data);
    },
    confirmHandle: function (vu, callback) {
      callback();
    },

    doExportTableFile: function () {
      inforesApi.exportDbStructSurfaceData(this.resGuid,this.lastTakeEffectedConditionArr).then((result)=>{
        let blob = new Blob([result],{
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.style.display = 'none';
        downloadElement.download =`${this.resTitle}.xlsx`;
        downloadElement.href = href;
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      })
    },

    //导入数据
    importTableData: function () {
      let tableHearders = [];
      for (let i = 0; i < this.tableData.length; i++) {
        const element = this.tableData[i];
        const cruheard = {"prop": element.fieldName, "title": element.fieldTitle,"isOptionalConditionFields":true}
        tableHearders.push(cruheard);
      }

      let url = this.$rootUrl + "/ires/importPreData/impTableDatas";
      let that = this;
      let options = {
        id: 'impTableDatas',
        title: "导入数据",
        width: 500,
        height: 212,
        draggable: true,
        ajaxConfirm: true,
        url: url,
        initValue: {
          resGuid: this.resGuid,
          tableHearders: tableHearders
        },
        buttons: [{
          text: "导入", id: 'bsp-confirmButton', async: true, click: function (btn, handler) {
            var frame = this.find('iframe[biFrameDialog=true]')[0];
            var returnFunction = frame.contentWindow['confirmHandle'];

            if ($.isFunction(returnFunction)) {
              if ($.isFunction(handler)) {
                returnFunction('ok', function (result) {
                  if (result === false) {
                    handler(false);
                    return;
                  }
                  handler(that.doImportTableFile(result));
                });
              }
            }
          }
        }],
      }
      this.$BiTopWin.$.bi.ui.frameDialog(options);
    },


    doImportTableFile: function (result) {
      $.bi.ui.closeDialog('impTableDatas', window);
      this.currentPage = 1;
      this.doFilterSearch();
    },

    clearTableDatas: function () {
      let _this = this;

      let info = "此操作会删除表中所有数据，继续操作请输入OK并点击确定";
      _this.$BI.Dialog.warn(info,() => {
        inforesApi.dataManageClearDatas( _this.resGuid).then(() => {
          _this.doFilterSearch();
        });
      }, "确认删除", {ok: true, height: 230});
    },
    addData: function () {
      this.curProcessType = 0

      let url = this.$rootUrl + "/ires/dataManager/addData";
      let options = {
        id: 'addData',
        title: "新建数据",
        width: 650,
        height: 500,
        draggable: true,
        ajaxConfirm: true,
        url: url,
        initValue: {
          filedInfos: this.tableHearders,
          resGuid: this.resGuid,
          curTablePKNameArr:this.curTablePKNameArr,
          curProcessType:this.curProcessType
        },
        returnValueFunctionName: 'confirmHandle',
        confirmCallback: this.dataCallback,
      }
      this.$BiTopWin.$.bi.ui.frameDialog(options);


    },
    modifyData: function () {
      this.curProcessType = 1

      let url = this.$rootUrl + "/ires/dataManager/modifyData";
      let options = {
        id: 'modifyData',
        title: "编辑数据",
        width: 650,
        height: 500,
        draggable: true,
        ajaxConfirm: true,
        url: url,
        initValue: {
          filedInfos:this.tableHearders,
          resGuid: this.resGuid,
          curSelectedItem: this.multipleTableSelection[0],
          curTablePKNameArr:this.curTablePKNameArr,
          curProcessType:this.curProcessType
        },
        returnValueFunctionName: 'confirmHandle',
        confirmCallback: this.dataCallback,
      }
      this.$BiTopWin.$.bi.ui.frameDialog(options);

    },
    typeProcess(callbackItem,originalModifyValue) {
      return new Promise((resolve)=>{

        if (this.curProcessType === 1){
          let oldRowIndex = this.findOneRowIndex(this.tableData, originalModifyValue);
          this.tableData.splice(oldRowIndex,1, callbackItem)
          resolve()
        }

        if (this.curProcessType === 0){
          this.doFilterSearch().then(()=>{
            let lastPageNum = Math.ceil(this.currentTotal / this.pageSize)

            inforesApi.dataManageQueryByFilter(this.resGuid, lastPageNum, this.pageSize, this.lastTakeEffectedConditionArr).then((res) => {
              this.currentPage = lastPageNum
              this.tableData = res.data;

              let oneRowIndex = this.findOneRowIndex(this.tableData, callbackItem);

              if (oneRowIndex !== -1) {
                this.tableData.splice(oneRowIndex, 1)
              } else {
                 this.tableData.splice(0, 1)
              }

              this.tableData.push(callbackItem)
              resolve()
            })
          })
        }
      })
    },
    dataCallback: function (callbackInfo) {
      let callbackItem = {}
      let originalModifyValue = {}

      if (this.curProcessType === 0) {
        callbackItem = callbackInfo
        callbackItem.isSelectedViewTarget = true
      }

      if (this.curProcessType === 1) {
        callbackInfo = JSON.parse(callbackInfo)
        callbackItem = callbackInfo.modifyItem
        originalModifyValue = callbackInfo.originalModifyValue
      }

      this.typeProcess(callbackItem, originalModifyValue).then(() => {
        if (this.curProcessType === 0) {
          this.$nextTick(() => {
            const scrollIntoViewTarget = document.getElementsByClassName('datamanageTreeScrollIntoViewTableItemTarget')[0];
            if (scrollIntoViewTarget) {
              const tableBodyWrapper = scrollIntoViewTarget.closest('.el-table__body-wrapper');

              if (tableBodyWrapper) {
                setTimeout(() => {
                  tableBodyWrapper.scrollTo({
                    top: tableBodyWrapper.clientHeight,
                    behavior: 'smooth'
                  });

                  //避免影响后续操作（删除、编辑）
                  delete callbackItem.isSelectedViewTarget
                }, 400);
              }
            }
          })
        }
      })
    },
    findOneRowIndex(tableData,tableItem){
      return tableData.findIndex(item => {
        // 检查两个对象的所有属性是否相等
        const keys2 = Object.keys(item);

        // 遍历属性并检查值是否相等
        for (let key of keys2) {
          if (tableItem[key] !== item[key]) return false;
        }

        // 所有属性都匹配
        return true;
      });
    },
    deleteData: function () {
      this.$BI.Dialog.confirm("确认删除当前已选项吗？", () => {
        this.deleteConfirm()
      });
    },
    deleteConfirm:function (){
      //以主键进行删除
      if (this.curTablePKNameArr.length > 0){
        let deleteParamArr = []
        for (const selectedRow of this.multipleTableSelection) {
          let oneRowDeleteParam = []
          for (const onePKName of this.curTablePKNameArr) {
            oneRowDeleteParam.push(selectedRow[onePKName]);
          }
          deleteParamArr.push(oneRowDeleteParam);
        }

        let deleteParam = {
          'curTablePKNameArr':this.curTablePKNameArr,
          'deleteParamArr':deleteParamArr
        }

        inforesApi.dataManageDeleteDataByPK(this.resGuid,deleteParam).then((res)=>{
          if (res.processSuccess){
            this.doFilterSearch()
            this.$BI.Dialog.success("删除成功");
          } else{
            this.$BI.Dialog.error(res.errorInfo);
          }
        });
      }else {
        inforesApi.dataManageDeleteDataByAllFields(this.resGuid,this.multipleTableSelection).then((res)=>{
          if (res.processSuccess){
            this.doFilterSearch()
            this.$BI.Dialog.success("删除成功");
          }else{
            this.$BI.Dialog.error(res.errorInfo);
          }
        })
      }
    },
    //条件中选字段
    selectTableField:function (curConditionId,fieldItem){
      const curCondition = this.conditionArr.find(processItem=>{
        return processItem.id === curConditionId
      })

      if (curCondition.name !== ''){
        this.optionalTableHeaders.find(processItem=>{
          return processItem.prop === curCondition.name
        }).isOptionalConditionFields = true
      }

      //更新条件
      curCondition.title = fieldItem.title
      curCondition.name = fieldItem.prop

      //现选字段设置不可选
      this.optionalTableHeaders.find(processItem=>{
        return processItem.prop === fieldItem.prop
      }).isOptionalConditionFields = false;
    },
    deleteCondition:function (condition){

      this.optionalTableHeaders.find(processItem=>{
        return processItem.prop === condition.name
      }).isOptionalConditionFields = true;

      const toRemoveConditionIndex = this.conditionArr.findIndex(processItem=>{
        return processItem.id === condition.id
      })
      this.conditionArr.splice(toRemoveConditionIndex, 1);

      if (this.conditionArr.length === 0){
        this.lastTakeEffectedConditionArr.splice(0, this.lastTakeEffectedConditionArr.length);
        this.doFilterSearch();
      }

      let conditionRowCount = Math.ceil(this.conditionArr.length / 3);

      //查询按钮是否换行
      let isSearchButtonInAnotherRow = conditionRowCount !== 0 && this.conditionArr.length % 3 === 0;

      if (isSearchButtonInAnotherRow)
        this.struceOptionalExcel = (conditionRowCount + 1) * 43 + 60;
      else
        this.struceOptionalExcel = conditionRowCount * 43 + 60;
    },
    addFilterCondition: function () {
        //一定能找出一个可选择的字段
      let optionalConditionField = this.optionalTableHeaders.find(processItem=>{
        return processItem.isOptionalConditionFields === true
      })
        let conditionObj = {
          id: this.conditionArr.length + 1,
          name: optionalConditionField.prop,
          title : optionalConditionField.title,
          value : '',
        }
        this.conditionArr.push(conditionObj);
      optionalConditionField.isOptionalConditionFields = false

      //设置表格区域高度
      let conditionRowCount = Math.ceil(this.conditionArr.length / 3);
      //查询按钮是否换行
      let isSearchButtonInAnotherRow = this.conditionArr.length % 3 === 0;

      if (isSearchButtonInAnotherRow)
        this.struceOptionalExcel = (conditionRowCount + 1) * 43 + 60;
      else
        this.struceOptionalExcel = conditionRowCount * 43 + 60;
    },
    doFilterSearch:function (){
      return new Promise((resolve) => {
        let _this = this
        _this.isloading = true;
        inforesApi.dataManageQueryByFilter(_this.resGuid, _this.currentPage, _this.pageSize, _this.lastTakeEffectedConditionArr).then((res1) => {
          let curTotalSize = res1.totalSize;
          //总数不为零时，当前页 超过了查询最大 页数，需要再查询一次，指向当前合法最大页数
          if (curTotalSize > 0 && _this.currentPage * _this.pageSize > curTotalSize) {
            let currentPage = Math.ceil(curTotalSize / _this.pageSize);
            inforesApi.dataManageQueryByFilter(_this.resGuid, currentPage, _this.pageSize, _this.lastTakeEffectedConditionArr).then((res2) => {
              _this.currentPage = currentPage
              _this.currentTotal = curTotalSize;
              _this.tableData = res2.data;
              _this.isloading = false;
              resolve()
            })
          } else {
            _this.tableData = res1.data;
            _this.currentTotal = curTotalSize;
            _this.isloading = false;
            resolve()
          }
        })
      })
    },
    activeFilterCondition: function () {
      this.lastTakeEffectedConditionArr = JSON.parse(JSON.stringify(this.conditionArr))
      this.doFilterSearch()
    }
  },
  mounted() {
    let dialogId = this.$route.params.dialogId;
    if (dialogId) {
      let values = this.$BiTopWin.$.bi.ui.getFrameDialogValues(dialogId);
      if (values.resGuid) {
        this.resGuid = values.resGuid;
      }
      if (values.resType) {
        this.resType = values.resType;
      }
      if (values.resTitle) {
        this.resTitle = values.resTitle;
      }

      window.confirmHandle = this.confirmHandle;
    } else {
      this.resGuid = this.resCode;
      this.resType = this.cruResType;
      this.resTitle = this.cruResTitle
    }

    if (this.resType == 'table_dim') {

      let cruDialog = this.$BiTopWin.$.bi.ui.getDialogById(dialogId);
      cruDialog[0].previousSibling.style.zIndex = 999;
      cruDialog.css("z-index", "1000");
      this.initDimData();
    } else {
      if (this.resGuid) {
        this.initStructFiled();
        this.$nextTick(() => {
          this.doFilterSearch();
        });
      }
    }


    inforesApi.getStructureTabData({"resGuid": this.resGuid}).then((res) => {
      let PKFieldStructures = res.data.structure.filter(oneStructure=>{
        return oneStructure.isPrimaryKey === true
      })
        this.curTablePKNameArr = PKFieldStructures.map(oneStructure=>oneStructure.fieldName)
    });

    this.curProcessType = -1
  },
}

</script>

<style scoped>
.upload_struct_optinal_btn {
  float: left;
  height: 32px;
  line-height: 32px;
  margin: 12px;
}

.upload_struct_optinal_btn .bi-el-btn {
  height: 32px;
  padding: 4px 15px !important;
}

.struce-optional-excel {
  margin-right: 16px;
  margin-left: 16px;
  width: calc(100% - 32px);
}
#export-data-preview{
  height: 98%;
  display: flex;
  flex-direction: column;
  align-items: start;
}
#export-data-preview-div {
  height: 100%;
}

#export-data-preview-dim {
  height: calc(100% - 10px);
}

#iresinfoDimView #header-btn-group-top {
  display: none;
}
.filterAreaClass{
  margin-right: 16px;
  margin-left: 16px;
  width: calc(100% - 32px);
  height: auto;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.conditionClass {
  width: 33.3%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-bottom: 12px;
}
.conditionSelectClass{
  width: 55%;
}
.conditionSelectClass .el-dropdown-menu{
  min-width: 55%;
}
.conditionSelectButtonClass{
  width: 150px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
